#include "guimgr.h"
#include "guiwindow.h"

CGuiManager::CGuiManager()
{
	m_bEnabled = false;
}

CGuiManager::~CGuiManager()
{
	m_bEnabled = false;

	for(uint32_t i = 0; i < m_vWindows.size(); ++i)
	{
		delete m_vWindows[i];
		m_vWindows[i] = NULL;
	}
}
typedef std::vector<CGuiWindow*>::iterator windowIterator;

void CGuiManager::Update()
{
	uint32_t startIndex = m_vWindows.size()-1;
	for(int32_t i = startIndex; i >= 0; --i)
	{
		m_vWindows[i]->Update();
		if(i != m_vWindows.size()-1)
			m_vWindows[i]->SetColor(50, 125, 192, 150);
	}

	for(int32_t i = startIndex; i >= 0; --i)
	{
		bool alreadyDragging = false;
		for(int32_t j = startIndex; j >= 0; --j)
		{
			if(j < 0)
				break;

			if(m_vWindows[j]->m_bDragging)
			{
				alreadyDragging = true;
				break;
			}
		}

		if(alreadyDragging)
			break;

		if(m_vWindows[i]->IsDraggable())
		{
			SetWindowFocus(i);
			m_vWindows[i]->m_bDragging = true;
			break;
		}

		if(m_vWindows[i]->IsSelectable() && m_vWindows[i]->IsMouseDown())
		{
			SetWindowFocus(i);
			break;
		}
	}

	for(int i = startIndex; i >= 0; --i)
	{
		if(!m_vWindows[i]->IsMouseDown())
			m_vWindows[i]->m_bDragging = false;
	}
}

void CGuiManager::Render()
{
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	uint32_t size = m_vWindows.size();
	for(uint32_t i = 0; i < size; ++i)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_DEPTH_TEST);
		m_vWindows[i]->Render();
		glDisable(GL_BLEND);
	}

	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	
}

void CGuiManager::AddWindow(CGuiWindow* pWindow)
{
	m_vWindows.push_back(pWindow);
	SetWindowFocus(m_vWindows.size()-1);
}

void CGuiManager::SetWindowFocus(uint32_t index)
{
	//	Sanity check
	if(index >= m_vWindows.size())
		return;

	CGuiWindow* oldWindow = m_vWindows[m_vWindows.size()-1];
	oldWindow->SetColor(50, 125, 192, 150);
	m_vWindows[m_vWindows.size()-1] = m_vWindows[index];
	m_vWindows[index] = oldWindow;

	m_vWindows[m_vWindows.size()-1]->SetColor(36, 135, 172, 250);	//	Unreal Food Pills
}

void CGuiManager::RenderViewport(vec2f& pos, vec2f& size)
{
	int32_t winX, winY;
	winX = winY = 0;
	glfwGetWindowSize(&winX, &winY);

	glViewport(static_cast<GLsizei>(pos.x), 
			static_cast<GLsizei>(winY-pos.y-size.y), 
			static_cast<GLint>(size.x), 
			static_cast<GLint>(size.y));
	
	//	Quad
	glBegin(GL_QUADS);
	glTexCoord2f(0, 0);
	glVertex2f(-1.0, -1.0);
	glTexCoord2f(0, 1);
	glVertex2f(1.0, -1.0);
	glTexCoord2f(1, 1);
	glVertex2f(1.0, 1.0);
	glTexCoord2f(1, 0);
	glVertex2f(-1.0, 1.0);
	glEnd();
}

void CGuiManager::GetClientArea(int32_t& width, int32_t& height)
{
	glfwGetWindowSize(&width, &height);
}
